//
//  DWLoadingStateKey.swift
//  DWSwift
//
//  Created by GDL on 2025/6/24.
//

import Foundation
import SwiftUI

public final class DWGlobalLoadingState: ObservableObject {
    
    public static let shared = DWGlobalLoadingState.init()
    
    @Published var isLoading = false
    
    private var requestQueue = DispatchQueue(label: "com.dwloading.queue", attributes: .concurrent)
    
    private var requestCount = 0 {
        didSet { isLoading = requestCount > 0 }
    }
    
    // 加入队列（线程安全）
    func startLoading() {
        requestQueue.async(flags: .barrier) {[weak self] in
            guard let self = self else { return }
            // 确保在主线程更新
            DispatchQueue.main.async {
                self.requestCount += 1
            }
            
            // 15秒超时检测
//            DispatchQueue.main.asyncAfter(deadline: .now() + 15) {
//                self.stopLoading()
//            }
        }
    }
    
    // 离开队列（自动检测空队列）
    func stopLoading() {
        requestQueue.async(flags: .barrier) {[weak self] in
            guard let self = self else { return }
            // 确保在主线程更新
            DispatchQueue.main.async {
                self.requestCount = max(0, self.requestCount - 1)
            }
        }
    }
    
}

//// 环境对象 Key 定义
//struct DWLoadingEnvironmentKey: EnvironmentKey {
//    static var defaultValue: DWGlobalLoadingState? = nil
//}
//
//extension EnvironmentValues {
//    var loadingStateDWG: DWGlobalLoadingState? {
//        get { self[DWLoadingEnvironmentKey.self] }
//        set { self[DWLoadingEnvironmentKey.self] = newValue }
//    }
//}
